<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';

import { message } from 'ant-design-vue';

import { auto1688stor } from '#/store';
import { in1688ToDoudianStore } from '#/store/modules';

import { checkBeforePublish } from './addInSysProduct';
import setMiniBox from './setMiniBox.vue';
import { getStrLen } from './tools';

interface IProps {
  selectItemList: any[];
  shopId?: string;
  tbId?: string;
}
defineOptions({
  name: 'SetAddProductBox',
});
const props = defineProps<IProps>();
const open = defineModel();

const auto1688storTres = auto1688stor();
const in1688ToDoudian: any = in1688ToDoudianStore();

const getInStoreBindShops: any = computed(() =>
  auto1688storTres.auto1688.bindShopList?.filter((item: any) => {
    item.label = item.shopName;
    item.value = item.shopId;
    return item.pType === 2;
  }),
);

const isNowShowData = ref<boolean>(false);

const openDrawer = ref(false);
const nowData = computed(() => auto1688storTres.auto1688.nowSelectDyShop);
function addProduct() {
  checkBeforePublish(in1688ToDoudian.shopTabs);
}
const showSelectBox = ref(false);

onMounted(() => {
  if (props.shopId) {
    in1688ToDoudian.setselectShop(props.shopId);
    openSelectDeit();
    showSelectBox.value = false;
    return false;
  }
  // in1688ToDoudian.selectShop = nowData.value.shopId;
  in1688ToDoudian.setselectShop([nowData.value.shopId]);
  const getItemter = localStorage.getItem('isNowShowData');

  if (getItemter) {
    showSelectBox.value = false;
    isNowShowData.value = true;
    openSelectDeit();
    return false;
  }

  // console.log('in1688ToDoudian.selectShop.values', nowData);
  if (getInStoreBindShops.value?.length === 1) {
    // in1688ToDoudian.selectShop.values = [getInStoreBindShops.value[0].value];
    in1688ToDoudian.setselectShop(getInStoreBindShops.value[0].value);
    openSelectDeit();
    showSelectBox.value = false;
    return false;
  }

  showSelectBox.value = true;
});
/** ** 测试 */
let old: any = null;
function openSelectDeit() {
  if (in1688ToDoudian.selectShop.length === 0) {
    return message.error('请选择铺货店铺');
  }
  in1688ToDoudian.setSelectData({
    selectGoods: props.selectItemList,
    tbId: props.tbId,
  });
  openDrawer.value = true;
  showSelectBox.value = false;

  if (isNowShowData.value) {
    localStorage.setItem('isNowShowData', '1');
  }
  // console.log('openDrawer', openDrawer.value);
}
function clearBox() {
  openDrawer.value = false;
  showSelectBox.value = false;
  open.value = false;
}
let jieliu: any = null;

let selectShopList: any = [];
let jeliu: any = null;
in1688ToDoudian.$subscribe((_mutation: any, state: any) => {
  // console.log('state', state);
  if (jeliu) return;
  jeliu = setTimeout(() => {
    clearTimeout(jeliu);
    jeliu = null;
  }, 500);

  if (JSON.stringify(selectShopList) !== JSON.stringify(state.selectShop)) {
    // eslint-disable-next-line unicorn/prefer-structured-clone
    selectShopList = JSON.parse(JSON.stringify(state.selectShop));
    return;
  }
  if (state.shopTabs.length <= 0) {
    clearBox();
    return;
  }
  const getNowIndengt = state.shopTabs.findIndex(
    (item: any) => item.shopId === state.nowSelectTab,
  );
  // console.log('getNowIndengt', getNowIndengt);
  if (getNowIndengt === -1) {
    state.nowSelectTab = state.shopTabs[0].shopId;
  }
  if (old && JSON.stringify(state.shopTabs) === JSON.stringify(old)) {
    clearTimeout(jieliu);
    jieliu = null;
    return;
  }
  // eslint-disable-next-line unicorn/prefer-structured-clone
  old = JSON.parse(JSON.stringify(state.shopTabs));
  if (jieliu) {
    clearTimeout(jieliu);
    jieliu = null;
  }
  jieliu = setTimeout(() => {
    setErrListEach(state);
  }, 1000);
  // 监听是否关闭对应的弹窗
});

function setErrListEach(state: any) {
  // eslint-disable-next-line unicorn/prefer-structured-clone
  const copyJsons = JSON.parse(JSON.stringify(state.shopTabs));
  copyJsons.forEach((item: any) => {
    // console.log('item', item);
    item.productDetailList.forEach((item2: any) => {
      // console.log('item2', item2);

      item2.basisErrs = setbasisErrFun(item2);
      item2.picErrs = setPicErrFun(item2);
      item2.descErrs = setDescErrFun(item2);
      item2.priceErrs = setPriceErrFun(item2);
      item2.errAlls = (() => {
        const errAlls: any = {
          errNum: 0,
          errList: [],
        };
        errAlls.errNum =
          item2.basisErrs.errNum +
          item2.picErrs.errNum +
          item2.descErrs.errNum +
          item2.priceErrs.errNum;
        errAlls.errList = [
          ...item2.basisErrs.errList,
          ...item2.picErrs.errList,
          ...item2.descErrs.errList,
          ...item2.priceErrs.errList,
        ];
        return errAlls;
      })();
      // const priceInventoryErrs = {};
      // item2.priceInventoryErrs = priceInventoryErrs;
    });
  });
  state.shopTabs = copyJsons;
  function setbasisErrFun(item: any) {
    const basisErrs: any = {
      errNum: 0,
      errList: [],
    };
    if (!item.categoryId) {
      basisErrs.errNum++;
      basisErrs.errList.push({
        key: 'categoryId',
        msg: '请选择商品分类',
      });
    }
    if (item.goodsTitle) {
      const maxlen =
        item.rule?.recommendNameRule?.titleLimitRule?.maxLength || 60;
      const minlen =
        item.rule?.recommendNameRule?.titleLimitRule?.minLength || 15;
      if (
        getStrLen(item.goodsTitle) > maxlen ||
        getStrLen(item.goodsTitle) < minlen
      ) {
        basisErrs.errNum++;
        basisErrs.errList.push({
          key: 'goodsTitle',
          msg: `商品标题长度在${minlen}~${maxlen}字符之间`,
        });
      }
    } else {
      basisErrs.errNum++;
      basisErrs.errList.push({
        key: 'goodsTitle',
        msg: '商品标题不能为空',
      });
    }
    // console.log(' item.propertyList', item.propertyList);
    item.propertyList?.forEach((item3: any) => {
      // console.log('item3', item3);
      if (item3.required) {
        if (item3.type === 'multi_value_measure') {
          let moboter = 0;
          // 对 item3.optionsValue 的veuls 求和
          let noData = false;
          item3.optionsValue.forEach((item4: any) => {
            moboter += item4.value;
            if (!item4.valueId) {
              noData = true;
            }
          });
          if (noData) {
            basisErrs.errNum++;
            basisErrs.errList.push({
              key: 'propertyList',
              msg: `属性 <${item3.propertyName}>的值不能为空`,
            });
          }
          if (moboter * 1 !== 100) {
            basisErrs.errNum++;
            basisErrs.errList.push({
              key: 'propertyList',
              msg: `属性<${item3.propertyName}>的值必须为100`,
            });
          }
          return;
        }
        if (item3.type === 'multi_select' && item3.optionsValue.length === 0) {
          basisErrs.errNum++;
          basisErrs.errList.push({
            key: 'propertyList',
            msg: `属性<${item3.propertyName}>的值不能为空`,
          });
          return;
        }
        if (item3.type === 'measure') {
          // console.log('item3.optionsValue', item3);
          item3.measureTemplates.forEach((item4: any) => {
            item4.valueModules.forEach((item5: any) => {
              if (!item5.value) {
                basisErrs.errNum++;
                basisErrs.errList.push({
                  key: 'propertyList',
                  msg: `属性<${item3.propertyName}>的值不能为空`,
                });
              }
            });
          });

          return;
        }
        if (!item3.optionsValue || item3.optionsValue.length === 0) {
          basisErrs.errNum++;
          basisErrs.errList.push({
            key: 'propertyList',
            msg: `属性<${item3.propertyName}>的值不能为空`,
          });
        }
      }
    });

    return basisErrs;
  }
  function setPicErrFun(item: any) {
    const picErrs: any = {
      errNum: 0,
      errList: [],
    };
    if (!item.mainPicList || item.mainPicList.length < 3) {
      picErrs.errNum++;
      picErrs.errList.push({
        key: 'mainPicList',
        msg: '商品主图不能少于3张',
      });
    }
    return picErrs;
  }
  function setDescErrFun(item: any) {
    const descErrs: any = {
      errNum: 0,
      errList: [],
    };
    if (!item.descPicList || item.descPicList.length === 0) {
      descErrs.errNum++;
      descErrs.errList.push({
        key: 'descPicList',
        msg: '商品详情图不能为空',
      });
    }
    return descErrs;
  }
  function setPriceErrFun(item: any) {
    const { specInfo, specPricesV2 } = item;
    const priceErrs: any = {
      errNum: 0,
      errList: [],
    };
    if (!specInfo || !specPricesV2) {
      return priceErrs;
    }
    specInfo.specValues.forEach((item1: any) => {
      if (item1.isRequired) {
        if (item1.values.length === 0) {
          priceErrs.errNum++;
          priceErrs.errList.push({
            key: 'specInfo',
            msg: `规格<${item1.sellPropertyName}>的值不能为空`,
          });
        } else {
          item1.values.forEach((item2: any, index: number) => {
            if (!item2.valueName || !item2.valueId) {
              priceErrs.errNum++;
              priceErrs.errList.push({
                key: 'specInfo',
                msg: `规格<${item1.sellPropertyName}>的第<${index + 1}项>规格值不能为空`,
              });
            }
          });
        }
      }
      if (item1.iserror) {
        priceErrs.errNum++;
        priceErrs.errList.push({
          key: 'specInfo',
          msg: `存在不符合下游平台规范的规格名<${item1.sellPropertyName}>`,
        });
      }
    });
    specPricesV2.forEach((item3: any) => {
      if (!(item3.price * 1)) {
        priceErrs.errNum++;
        priceErrs.errList.push({
          key: 'specPricesV2',
          msg: `sku<${item3.sellProperties.map((item4: any) => item4.valueName).join('--')}>的价格不能为空`,
        });
      }
    });
    return priceErrs;
  }
}
</script>

<template>
  <div>
    <a-drawer
      :body-style="{ paddingBottom: '80px' }"
      :footer-style="{ textAlign: 'right' }"
      :open="openDrawer"
      :width="1000"
      title="铺货预览"
      @close="clearBox"
    >
      <template #footer>
        <!-- <a-button style="margin-right: 8px">Cancel</a-button> -->
        <a-button
          :disabled="in1688ToDoudian.lodingBool || in1688ToDoudian.ingetdeteail"
          :loading="in1688ToDoudian.lodingBool || in1688ToDoudian.ingetdeteail"
          type="primary"
          @click="addProduct"
        >
          立即铺货
        </a-button>
      </template>
      <a-spin :spinning="in1688ToDoudian.lodingBool" tip="正在铺货中...">
        <setMiniBox v-if="openDrawer" />
      </a-spin>
    </a-drawer>
    <a-modal
      :open="showSelectBox"
      title="选择铺货店铺"
      @cancel="clearBox"
      @ok="openSelectDeit"
    >
      <template #footer>
        <a-space>
          <a-checkbox v-model:checked="isNowShowData">
            默认使用当前选择店铺以后不再提醒
          </a-checkbox>
          <a-button @click="clearBox">取消</a-button>
          <a-button type="primary" @click="openSelectDeit">确定</a-button>
        </a-space>
      </template>
      <a-checkbox-group
        v-model:value="in1688ToDoudian.selectShop"
        :options="getInStoreBindShops"
      />
    </a-modal>
  </div>
</template>
